import json
from django.shortcuts import render
from django.http import HttpResponseRedirect
from userapp.models import *

# 获取用户信息
def get_user_cls(userId):
    user_dict = {}
    if userId:
        usertab = UserTab.objects.get(id=userId)
        user_dict["userName"] = usertab.userName
        user_dict["userId"] = usertab.id
        menuList = usertab.menu.split("、")
        user_dict["menuList"] = menuList
    return user_dict


def LoginCls(request):
    res_data = {
        "status": 1,
        "data": {}
    }
    if request.method == 'POST':
        params = request.POST
        username = params["username"]
        password = params["password"]
        user_tab = UserTab.objects.filter(userName=username, password=password)
        if user_tab.count() > 0:
            userId = user_tab[0].id
            userName = user_tab[0].userName
            return HttpResponseRedirect(f"/home/?userName={userName}&userId={userId}")
        else:
            res_data['message'] = "用户名或密码有误！"
    else:
        res_data['message'] = "用户名或密码有误！"
    return render(request, 'login.html', res_data)


def RegisterCls(request):
    res_data = {
        "status": 1,
        "message": "",
        "data": {}
    }
    if request.method == 'POST':
        params = request.POST
        username = params["username"]
        password = params["password"]
        #repassword = params["repassword"]
        email = params["email"]
        if UserTab.objects.filter(userName=username).count() == 0:
            user_tab = UserTab(
                userName=username,
                password=password,
                email=email,
                menu="首页"
            )
            user_tab.save()
            res_data["message"] = "注册成功"
            userId = user_tab.id
            userName = user_tab.userName
            return HttpResponseRedirect(f"/home/?userName={userName}&userId={userId}")
        else:
            res_data = {
                "status": 0,
                "message": f"{username}已经被注册过了！",
                "data": {}
            }
    return render(request, 'register.html', res_data)

def UserCls(request):
    res_data = {
        "status": 1,
        "data": {}
    }
    userId = request.GET.get("userId")
    user_dict = get_user_cls(userId)
    res_data["user"] = user_dict
    page = request.GET.get("page")
    if page:
        page = int(page)
    else:
        page = 1
    pageSize = request.GET.get("pageSize")
    if pageSize:
        pageSize = int(pageSize)
    else:
        pageSize = 20
    usertab = UserTab.objects.all()
    totalNum = usertab.count()
    usertab = usertab[(page-1)*pageSize:page*pageSize]
    userList = []
    num = (page-1)*pageSize + 1
    for data in usertab:
        userList.append({
            "num": num,
            "userId": data.id,
            "userName": data.userName,
            "password": data.password,
            "email": data.email,
            "menu": data.menu
        })
        num = num + 1
    res_data["data"]["totalNum"] = totalNum
    res_data["data"]["userList"] = userList
    return render(request, 'users.html', res_data)

def MenuCls(request):
    res_data = {
        "status": 1,
        "data": {}
    }
    userId = request.GET.get("userId")
    user_dict = get_user_cls(userId)
    res_data["user"] = user_dict
    page = request.GET.get("page")
    if page:
        page = int(page)
    else:
        page = 1
    pageSize = request.GET.get("pageSize")
    if pageSize:
        pageSize = int(pageSize)
    else:
        pageSize = 1
    menutab = MenuTab.objects.all()
    totalNum = menutab.count()
    usertab = menutab[(page - 1) * pageSize:page * pageSize]
    menuList = []
    for data in usertab:
        menuList.append({
            "menuId": data.id,
            "label": data.label,
            "menu": data.menu
        })
    res_data["data"]["totalNum"] = totalNum
    res_data["data"]["menuList"] = menuList
    return render(request, 'menu.html', res_data)

def UserAddCls(request):
    res_data = {
        "status": 1,
        "data": {}
    }
    userId = request.GET.get("userId")
    user_dict = get_user_cls(userId)
    res_data["user"] = user_dict
    menutab = MenuTab.objects.all()
    menuList = []
    menu_dict = {}
    for data in menutab:
        menuList.append({
            "name": data.menu,
            "value": data.menuNum
        })
        menu_dict[data.menuNum] = data.menu
    res_data["menus"] = json.dumps(menuList)
    if request.method == 'POST':
        op = request.GET.get("op")
        params = request.POST
        userName = params["username"]
        password = params["password"]
        email = params["email"]
        menus = params["select"]
        if menus:
            menus_ll = []
            for menuNum in menus.split(","):
                menus_ll.append(menu_dict[int(menuNum)])
            menu = "、".join(menus_ll)
        else:
            menu = "首页"
        if op == "add":
            if UserTab.objects.filter(userName=userName).count() > 0:
                res_data["status"] = 0
                res_data["message"] = "用户已经存在请勿重复添加！"
            else:
                usertab = UserTab(
                    userName=userName,
                    password=password,
                    email=email,
                    menu=menu
                )
                usertab.save()
                return HttpResponseRedirect(f"/users/?userId={userId}")
    return render(request, 'userAdd.html', res_data)


def UserDelCls(request):
    userId = request.GET.get("userId")
    del_userId = request.GET.get("ID")
    if del_userId:
        UserTab.objects.filter(id=del_userId).delete()
    return HttpResponseRedirect(f"/users/?userId={userId}")


def UserChangeCls(request):
    res_data = {
        "status": 1,
        "data": {}
    }
    userId = request.GET.get("userId")
    user_dict = get_user_cls(userId)
    res_data["user"] = user_dict
    menutab = MenuTab.objects.all()
    menuList = []
    menu_dict = {}
    menuNum_dict = {}
    for data in menutab:
        menuList.append({
            "name": data.menu,
            "value": data.menuNum
        })
        menu_dict[data.menu] = data.menuNum
        menuNum_dict[data.menuNum] = data.menu
    res_data["menus"] = json.dumps(menuList)
    if request.method == "POST":
        params = request.POST
        changeId = params["changeId"]
        password = params["password"]
        email = params["email"]
        menus = params["select"]
        if menus:
            menus_ll = []
            for menuNum in menus.split(","):
                menus_ll.append(menuNum_dict[int(menuNum)])
            menu = "、".join(menus_ll)
        else:
            menu = "首页"
        UserTab.objects.filter(id=changeId).update(
            password=password,
            email=email,
            menu=menu
        )
        return HttpResponseRedirect(f"/users/?userId={userId}")
    else:
        # 修改的用户数据
        changeId = request.GET.get("changeId")
        changeUser = UserTab.objects.get(id=changeId)
        changeMenu = changeUser.menu
        menus_list = []
        for child in changeMenu.split("、"):
            menus_list.append(menu_dict[child])
        res_data["changeUser"] = {
            "userId": changeUser.id,
            "userName": changeUser.userName,
            "email": changeUser.email,
            "password": changeUser.password,
            "menu": changeUser.menu,
            "menusList": json.dumps(menus_list)
        }
    return render(request, 'userChange.html', res_data)

# 用户中心
def CenterCls(request):
    res_data = {
        "status": 1,
        "data": {}
    }
    userId = request.GET.get("userId")
    user_dict = get_user_cls(userId)
    res_data["user"] = user_dict
    if request.method == "POST":
        params = request.POST
        userName = params["username"]
        email = params["email"]
        password = params["password"]
        UserTab.objects.filter(id=userId).update(
            #userName=userName,
            email=email,
            password=password
        )
    usertab = UserTab.objects.get(id=userId)
    res_data["data"] = {
        "userId": usertab.id,
        "userName": usertab.userName,
        "password": usertab.password,
        "email": usertab.email,
        "menu": usertab.menu
    }
    return render(request, 'Center.html', res_data)